import { app, BrowserWindow } from 'electron';
import { isDev } from '../utils/env.js';
import { createMainWindow } from './window.js';
import { setupIpcHandlers } from './ipc.js';
import { setupSecurity } from '../utils/security.js';

// 添加日志记录
console.log('Starting application...');
console.log('Is development mode:', isDev);
console.log('App path:', app.getAppPath());
console.log('Current working directory:', process.cwd());
console.log('Resources path:', process.resourcesPath);

// 确保只有一个应用实例
const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
  console.log('Another instance is already running, quitting...');
  app.quit();
} else {
  let mainWindow;

  app.on('second-instance', () => {
    // 当运行第二个实例时，将会聚焦到 mainWindow 这个窗口
    console.log('Second instance detected, focusing main window');
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore();
      mainWindow.focus();
    }
  });

  // 创建主窗口
  const createWindow = async () => {
    console.log('Creating main window...');
    try {
      mainWindow = await createMainWindow();
      console.log('Main window created successfully');
      
      // 设置IPC处理程序
      setupIpcHandlers(mainWindow);
      console.log('IPC handlers set up');
      
      // 设置安全策略
      setupSecurity();
      console.log('Security policies set up');
      
      return mainWindow;
    } catch (error) {
      console.error('Failed to create main window:', error);
      app.quit();
    }
  };

  // 应用准备就绪时创建窗口
  app.whenReady().then(() => {
    console.log('App is ready, creating window...');
    createWindow();

    app.on('activate', () => {
      console.log('App activated');
      if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
      }
    });
  });

  // 所有窗口关闭时退出应用 (macOS除外)
  app.on('window-all-closed', () => {
    console.log('All windows closed');
    if (process.platform !== 'darwin') {
      app.quit();
    }
  });

  // 应用退出前清理
  app.on('before-quit', () => {
    console.log('App is about to quit');
    // 清理资源
  });
  
  // 添加全局错误处理
  process.on('uncaughtException', (error) => {
    console.error('Uncaught Exception:', error);
  });
  
  process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);
  });
}